import os
import hashlib
import random
import uuid
from multiprocessing import Pool
import time

BUFFER_SIZE = 65536  # 64KB

def calculate_md5(file_path):
    with open(file_path, 'rb') as file:
        md5_hash = hashlib.md5()
        while chunk := file.read(BUFFER_SIZE):
            md5_hash.update(chunk)
        return md5_hash.hexdigest()

def modify_md5(file_path):
    with open(file_path, 'ab') as file:
        uuid_code = str(uuid.uuid4())
        random_nums = ''.join(str(random.randint(0, 9)) for _ in range(10))
        data = bytes(uuid_code + random_nums, 'utf-8')
        file.write(data)

def process_file(file_path):
    old_md5 = calculate_md5(file_path)
    modify_md5(file_path)
    new_md5 = calculate_md5(file_path)
    if old_md5 != new_md5:
        print(f'{file_path}\t文件处理中，MD5值已更改。')
        return 1
    return 0

def batch_modify_md5(folder_path):
    total_modified = 0
    start_time = time.time()
    with Pool() as pool:
        for root, dirs, files in os.walk(folder_path):
            file_paths = [os.path.join(root, file) for file in files]
            results = pool.map(process_file, file_paths)
            total_modified += sum(results)
    end_time = time.time()
    print('\n任务处理完成！')
    print(f'成功修改了总共 {total_modified} 个视频的MD5值。')
    print(f'耗时：{end_time - start_time:.2f} 秒\n')

# 入口
if __name__ == '__main__':
    print("欢迎使用素材MD5批量修改助手!\n")
    print("by kuiwaiwai - 自 gitee.com/kuiwaiwai 开源\n")
    print("本软件仅供学习交流使用，一切使用软件可能造成的不良后果由使用者个人承担！\n")
    while True:
        folder_path = input('请输入要批量修改的文件夹路径，可直接从资源管理器地址栏复制(输入n结束)：\n')
        if folder_path.lower() == 'n':
            break
        batch_modify_md5(folder_path)